package io.kiki.stack.rpc.registry.sofa;

import com.alipay.sofa.registry.client.api.RegistryClient;
import com.alipay.sofa.registry.client.api.RegistryClientConfig;
import com.alipay.sofa.registry.client.provider.DefaultRegistryClient;
import com.alipay.sofa.registry.client.provider.DefaultRegistryClientConfigBuilder;
import io.kiki.stack.rpc.common.utils.StringUtils;
import io.kiki.stack.rpc.config.RegistryConfig;


public class SofaRegistryClient {

    public static final String LOCAL_DATACENTER = "DefaultDataCenter";
    public static final String LOCAL_REGION = "DEFAULT_ZONE";

    private static RegistryClient registryClient;

    public static synchronized RegistryClient getRegistryClient(String appName, RegistryConfig registryConfig) {
        if (registryClient == null) {
            String address = registryConfig.getAddress();
            final String portStr = StringUtils.substringAfter(address, ":");
            RegistryClientConfig registryClientConfig = DefaultRegistryClientConfigBuilder.start().setAppName(appName).setDataCenter(LOCAL_DATACENTER).setZone(LOCAL_REGION).setRegistryEndpoint(StringUtils.substringBefore(address, ":")).setRegistryEndpointPort(Integer.parseInt(portStr)).build();

            registryClient = new DefaultRegistryClient(registryClientConfig);
            ((DefaultRegistryClient) registryClient).init();
        }
        return registryClient;
    }
}